//
//  AboutViewController.m
//  MyTravel
//
//  Created by Hunk on 11-6-12.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "AboutViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "ShowWebViewController.h"

#define MESSAGEBODY @"<点击此处进行信息输入>"

#define TITLE_FEEDBACK @"意见反馈"
#define EMAIL_FEEDBACK @"myappfeedback@gmail.com"

#define TITLE_COOPERATION @"战略合作"
#define EMAIL_COOPERATION @"tuanyouworld@gmail.com"

#define TITLE_SINAWEIBO @"团游世界"
#define URL_WEIBO_TUANYOUWORLD @"http://weibo.com/2185584484"

@interface AboutViewController (Private)

-(void)addLabelOnCell:(UITableViewCell*)cell
            text:(NSString*)text
            frame:(CGRect)frame 
            bgColor:(UIColor*)bgColor 
            textColor:(UIColor*)textColor 
            fontOfSize:(UIFont*)fontOfSize 
            lineBreakMode:(UILineBreakMode)lineBreakMode 
            textAlignment:(UITextAlignment)textAlignment;

-(void)displayComposerSheet:(NSString*)emailAddress title:(NSString*)title;
-(void)launchMailAppOnDevice:(NSString*)emailAddress title:(NSString*)title;

- (void)loadData;

@end

@implementation AboutViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) 
    {
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if (!_engine)
    {
        _engine = [[OAuthEngine alloc] initOAuthWithDelegate:self];
        _engine.consumerKey = kOAuthConsumerKey;
        _engine.consumerSecret = kOAuthConsumerSecret;
    }

//    UIView* footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 42)];
//    
//    UIButton* logoutButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//    [logoutButton setFrame:CGRectMake(10, 0, 300, 42)];
//    [logoutButton setImage:[UIImage imageNamed:@"redBg.png"] forState:UIControlStateNormal];
//    [logoutButton setTitle:@"注销新浪微博" forState:UIControlStateNormal];
//    
//    
////    UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, 300, 41.5)];
////    [imageView setImage:[UIImage imageNamed:@"redBg.png"]];
////    imageView.layer.cornerRadius = 8.0;
////    imageView.layer.masksToBounds = YES;
//    
//    [footerView addSubview:logoutButton];
//    self.tableView.tableFooterView = footerView;
//    [footerView release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section)
    {
        case 0:
            return 1;
            break;
        case 1:
            return 3;
            break;
        case 2:
            return 1;
            break;
        case 3:
            return 1;
            break;
        default:
            break;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{	
	switch (indexPath.section)
    {
        case 0:
        {
            return 150.0f;
        }
            break;
        case 1:
        {
            return 50.0f;
        }
            break;
        case 2:
        {
            return 120.0f;
        }
            break;
        case 3:
        {
            return 42.0f;
        }
            break;
        default:
            break;
    }
    return 0.0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    switch (section)
    {
        case 3:
        {
            return @"设置";
        }
            break;
        default:
            break;
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    
    switch (indexPath.section) 
    {
        case 0:
        {
            cell.selectionStyle = UITableViewCellSelectionStyleNone;     
            
            [self addLabelOnCell:cell
                            text:@"团游世界"
                           frame:CGRectMake(0, 0, 300, 30)
                         bgColor:[UIColor clearColor]
                       textColor:[UIColor blackColor] 
                      fontOfSize:[UIFont systemFontOfSize:20] 
                   lineBreakMode:UILineBreakModeCharacterWrap
                   textAlignment:UITextAlignmentCenter];
            
            [self addLabelOnCell:cell
                            text:@"®"
                           frame:CGRectMake(185, -3, 20, 20)
                         bgColor:[UIColor clearColor]
                       textColor:[UIColor blackColor] 
                      fontOfSize:[UIFont systemFontOfSize:14] 
                   lineBreakMode:UILineBreakModeCharacterWrap
                   textAlignment:UITextAlignmentCenter];
            
            [self addLabelOnCell:cell
                            text:@"        “团游世界”为旅游者提供世界各国热门景点旅游线路，帮助中国旅游者做出更好的旅游选择。凭借简捷明快的旅游线路呈现方式，让用户在短时间内了解整个行程，通过比较做出合理的选择，既省心又省钱。"
                           frame:CGRectMake(5, 30, 290, 110)
                         bgColor:[UIColor clearColor]
                       textColor:[UIColor blackColor] 
                      fontOfSize:[UIFont fontWithName:@"AmericanTypewriter" size:16]
                   lineBreakMode:UILineBreakModeCharacterWrap
                   textAlignment:UITextAlignmentLeft];
        }
            break;
        case 1:
        {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            
            UIImage* image;
            NSString* textString;
            
            if(0 == indexPath.row)
            {
                image = [UIImage imageNamed:@"feedbackIcon.png"];
                textString = [NSString stringWithFormat:@"%@", TITLE_FEEDBACK];
            }
            else if(1 == indexPath.row)
            {
                image = [UIImage imageNamed:@"cooperationIcon.png"];
                textString = [NSString stringWithFormat:@"%@", TITLE_COOPERATION];
            }
            else
            {   
                image = [UIImage imageNamed:@"weiboIcon.png"];
                textString = [NSString stringWithFormat:@"%@", TITLE_SINAWEIBO];
            }
            
            UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, 50, 50)];
            [imageView setBackgroundColor:[UIColor clearColor]];
            [imageView setImage:image];
            [cell.contentView addSubview:imageView];
            [imageView release];
            
            [self addLabelOnCell:cell
                            text:textString
                           frame:CGRectMake(110, 5, 100, 40)
                         bgColor:[UIColor clearColor]
                       textColor:[UIColor blackColor] 
                      fontOfSize:[UIFont systemFontOfSize:20] 
                   lineBreakMode:UILineBreakModeCharacterWrap
                   textAlignment:UITextAlignmentLeft];
        }
            break;
        case 2:
        {   
            [self addLabelOnCell:cell
                            text:@"免责声明"
                           frame:CGRectMake(10, 0, 280, 30)
                         bgColor:[UIColor clearColor]
                       textColor:[UIColor blackColor] 
                      fontOfSize:[UIFont systemFontOfSize:20] 
                   lineBreakMode:UILineBreakModeCharacterWrap
                   textAlignment:UITextAlignmentCenter];
            
            [self addLabelOnCell:cell
                            text:@"             版权所有©2011 侵权必究\n如果我们在无意中侵犯了您的权利，请您在第一时间联系我们，我们将尽最大努力解决。"
                           frame:CGRectMake(10, 30, 280, 80)
                         bgColor:[UIColor clearColor]
                       textColor:[UIColor blackColor] 
                      fontOfSize:[UIFont systemFontOfSize:16] 
                   lineBreakMode:UILineBreakModeCharacterWrap
                   textAlignment:UITextAlignmentLeft];
        }
            break;
        case 3:
        {   
            UIButton* logoutButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [logoutButton setFrame:CGRectMake(0, 0, 300, 42)];
            logoutButton.layer.cornerRadius = 8.0;
            logoutButton.layer.masksToBounds = YES;
            [logoutButton setBackgroundImage:[UIImage imageNamed:@"redBg.png"] 
                                    forState:UIControlStateNormal];
            [logoutButton setBackgroundImage:[UIImage imageNamed:@"redBg.png"] 
                                    forState:UIControlStateSelected];
            [logoutButton setTitle:@"注销新浪微博" forState:UIControlStateNormal];
            [logoutButton.titleLabel setFont:[UIFont boldSystemFontOfSize:18]];
            [logoutButton addTarget:self action:@selector(logoutSinaWeibo:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:logoutButton];
        }
            break;
        default:
            break;
    }
    
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    switch (indexPath.section)
    {
        case 1:
        {
            Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
            if(0 == indexPath.row)
            {
                if(mailClass)
                {
                    if([mailClass canSendMail])
                        [self displayComposerSheet:EMAIL_FEEDBACK title:TITLE_FEEDBACK];
                    else
                        [self launchMailAppOnDevice:EMAIL_FEEDBACK title:TITLE_FEEDBACK];
                }
                else
                    [self launchMailAppOnDevice:EMAIL_FEEDBACK title:TITLE_FEEDBACK];
            }
            else if(1 == indexPath.row)
            {
                if(mailClass)
                {
                    if([mailClass canSendMail])
                        [self displayComposerSheet:EMAIL_COOPERATION title:TITLE_COOPERATION];
                    else
                        [self launchMailAppOnDevice:EMAIL_COOPERATION title:TITLE_COOPERATION];
                }
                else
                    [self launchMailAppOnDevice:EMAIL_COOPERATION title:TITLE_COOPERATION];
            }
            else
            {
                ShowWebViewController* showWebViewController = [ShowWebViewController alloc];
                showWebViewController.urlString = URL_WEIBO_TUANYOUWORLD;
                showWebViewController.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:showWebViewController animated:YES];
                [showWebViewController release];
                
//                WeiboClient* weiboClient = [[WeiboClient alloc] initWithTarget:self 
//                                                                        engine:[OAuthEngine currentOAuthEngine] 
//                                                                        action:@selector(postStatusDidSucceed:object:)];
//                
//                [weiboClient follow:2185584484];
            
//                if (!_engine)
//                {
//                    _engine = [[OAuthEngine alloc] initOAuthWithDelegate: self];
//                    _engine.consumerKey = kOAuthConsumerKey;
//                    _engine.consumerSecret = kOAuthConsumerSecret;
//                }
                
//                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//                if([userDefaults objectForKey:@"authData"])
//                {   
//                    [weiboClient follow:2185584484];
//                    
//                    [self performSelector:@selector(loadTimeline) withObject:nil afterDelay:0.5];
//                }
//                else
//                {
//                    [self performSelector:@selector(loadTimeline) withObject:nil afterDelay:0.5];
//                }
            }
        }
            break;
        case 2:
        {
        }
            break;            
        default:
            break;
    }
}

- (void)loadTimeline {
	UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: _engine delegate: self];
	
	if (controller) 
    {
		[self presentModalViewController: controller animated: YES];
    }
	else 
    {
        //		NSLog(@"Authenicated for %@..", _engine.username);
		[OAuthEngine setCurrentOAuthEngine:_engine];
		[self loadData];
	}
}

- (void)loadData {
	if (weiboClient) { 
		return;
	}
	weiboClient = [[WeiboClient alloc] initWithTarget:self 
											   engine:_engine
											   action:@selector(timelineDidReceive:obj:)];
	[weiboClient getFollowedTimelineSinceID:0 
							 startingAtPage:0 count:100];
}

- (void)timelineDidReceive:(WeiboClient*)sender obj:(NSObject*)obj
{
    if (sender.hasError) 
    {
        [sender alert];	
    }
    else
    {
        ALERT_GENERAL(@"‘团游世界’谢谢您的关注")
    }
}

//=====================================================================================================
#pragma mark OAuthEngineDelegate
- (void) storeCachedOAuthData: (NSString *) data forUsername: (NSString *) username {
	NSUserDefaults			*defaults = [NSUserDefaults standardUserDefaults];
	
	[defaults setObject: data forKey: @"authData"];
	[defaults synchronize];
    
    // 关注
    [weiboClient follow:2185584484];
}

- (NSString *) cachedOAuthDataForUsername: (NSString *) username {
	return [[NSUserDefaults standardUserDefaults] objectForKey: @"authData"];
}

- (void)removeCachedOAuthDataForUsername:(NSString *) username{
	NSUserDefaults			*defaults = [NSUserDefaults standardUserDefaults];
	
	[defaults removeObjectForKey: @"authData"];
	[defaults synchronize];
}

//=======================================================================================
#pragma mark OAuthSinaWeiboControllerDelegate
- (void) OAuthController: (OAuthController *) controller authenticatedWithUsername: (NSString *) username {
    //	NSLog(@"Authenicated for %@", username);
	[self loadTimeline];
}

- (void) OAuthControllerFailed: (OAuthController *) controller {
    //	NSLog(@"Authentication Failed!");
	//UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: _engine delegate: self];
	
	if (controller) 
		[self presentModalViewController: controller animated: YES];
	
}

- (void) OAuthControllerCanceled: (OAuthController *) controller {
    //	NSLog(@"Authentication Canceled.");
	//UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: _engine delegate: self];
	
	if (controller) 
		[self presentModalViewController: controller animated: YES];
	
}

#pragma mark -
#pragma mark Compose Mail
-(void)displayComposerSheet:(NSString*)emailAddress title:(NSString*)title
{
	MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
    picker.navigationBar.tintColor = TINTCOLOR;
	
	[picker setSubject:title];
	
	// Set up recipients
    [picker setToRecipients:[NSArray arrayWithObjects:emailAddress, nil]];
    
	// Fill out the email body text
	[picker setMessageBody:MESSAGEBODY isHTML:NO];
	
	[self presentModalViewController:picker animated:YES];
    [picker release];
}

#pragma mark -
#pragma mark Workaround
// Launches the Mail application on the device.
-(void)launchMailAppOnDevice:(NSString*)emailAddress title:(NSString*)title 
{	
	// Recipient(s)
	NSString* strRecipient = [NSString stringWithFormat:@"mailto:%@?subject=%@", emailAddress, title];
	
	// Mail body
	NSString* strBody = [NSString stringWithFormat:@"&body=%@", MESSAGEBODY];
	
	NSString* strEmail = [NSString stringWithFormat:@"%@%@", strRecipient, strBody];
	strEmail = [strEmail stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:strEmail]];
}

// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the message field with the result of the operation.
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
{		
    NSString* strSendEmailresult = nil;
    switch (result)
    {
        case MFMailComposeResultCancelled: 
            strSendEmailresult = @"操作已被取消";
            break;
        case MFMailComposeResultSaved:
            strSendEmailresult = @"邮件已被保存到草稿箱";
            break;
        case MFMailComposeResultSent:
            strSendEmailresult = @"邮件正在发送,请保持网络通畅";
            break;
        case MFMailComposeResultFailed:
            strSendEmailresult = @"邮件发送失败，请重新发送";
            break;
        default:
            break;
    }
    
	[self dismissModalViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark logoutSinaWeibo
- (void)logoutSinaWeibo:(id)sender
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if([userDefaults objectForKey:@"authData"])
    { 
        UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"注销新浪微博?"
                                                                 delegate:self
                                                        cancelButtonTitle:@"取消"
                                                   destructiveButtonTitle:@"注销"
                                                        otherButtonTitles:nil];
        actionSheet.tag = 11;
        actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
        [actionSheet showFromTabBar:self.tabBarController.tabBar];
        [actionSheet release];
    }
    else
    {
        UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"您没有登录新浪微博"
                                                                 delegate:self
                                                        cancelButtonTitle:@"好的"
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:nil];
        actionSheet.tag = 12;
        actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
        [actionSheet showFromTabBar:self.tabBarController.tabBar];
        [actionSheet release];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(actionSheet.tag == 11)
    {
        if(0 == buttonIndex) // 注销
        {
            NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults removeObjectForKey: @"authData"];
            [userDefaults synchronize];
        }
    }
}

#pragma mark -
#pragma mark addLabelOnCell
-(void)addLabelOnCell:(UITableViewCell*)cell
				 text:(NSString*)text
				frame:(CGRect)frame 
			  bgColor:(UIColor*)bgColor 
			textColor:(UIColor*)textColor 
		   fontOfSize:(UIFont*)fontOfSize 
		lineBreakMode:(UILineBreakMode)lineBreakMode 
		textAlignment:(UITextAlignment)textAlignment
{
	if(!bgColor) bgColor = [UIColor grayColor];
	if(!textColor) textColor = [UIColor blackColor];
	if(!fontOfSize) fontOfSize = [UIFont systemFontOfSize:16];
	if(!text) text = [NSString stringWithString:@"请输入Label内容"];
	
	UILabel* titleLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
	titleLabel.backgroundColor = bgColor;
	titleLabel.textColor = textColor;
	titleLabel.font = fontOfSize;
	titleLabel.lineBreakMode = lineBreakMode;
	titleLabel.textAlignment = textAlignment;
    titleLabel.numberOfLines = 10;
	titleLabel.text = text;
	[cell.contentView addSubview:titleLabel];
}
@end
